package com.cainiao.test;

import com.cainiao.bean.Department;
import com.cainiao.bean.Employees;
import com.cainiao.dao.DepartmentMapper;
import com.cainiao.dao.EmployeeMapperDao;
import com.cainiao.dao.EmployeesMappersPlus;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author shkstart
 * @create 2021-04-07 9:02
 */
public class MyBatisTestPlus {
    //emp
    @Test
    public void test1() throws IOException {
        //1. 获取SqlSessionFactory对象
        String resource = "conf/mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2. 获取SqlSession对象
        SqlSession session = sqlSessionFactory.openSession();
        try {
            //3. 获取接口实现对象
            //会为接口自动的创建一个代理对象，代理对象去执行增删改查方法
            EmployeesMappersPlus mapper = session.getMapper(EmployeesMappersPlus.class);
            //4. 调用方法
            Employees emp = mapper.getEmpById(2);
//            Employees emp = mapper.getEmpAndDept(2);
//            Employees emp = mapper.getEmpByIdStep(1);
            System.out.println(emp);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5. 关闭会话
            session.close();
        }
    }



    //dept
    @Test
    public void test2() throws IOException {
        //1. 获取SqlSessionFactory对象
        String resource = "conf/mybatis.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2. 获取SqlSession对象
        SqlSession session = sqlSessionFactory.openSession();
        try {
            //3. 获取接口实现对象
            DepartmentMapper mapper = session.getMapper(DepartmentMapper.class);
            //根据id查询部门
//            Department dep = mapper.getDepById(2);
            //根据id查询部门下的员工
            Department dept = mapper.getDeptByIDJoinEmp(2);
            //根据id查询部门下的员工。分页
//            Department dept = mapper.getDeptByIdStep(2);
            dept.getEmps().forEach(System.out::println);
            System.out.println(dept);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //5. 关闭会话
            session.close();
        }
    }
}
